import requests
import json

beaver = 'Bearer bce-v3/ALTAK-EX7eBRfzrn3kPimmyHUoZ/ca503f2aac3bdb0fa41e22af8a165e638362bbbb'
app_id = 'a14bbb64-6c82-4461-869c-337df1157041'

# 步骤一 获取conversation_id
url = "https://qianfan.baidubce.com/v2/app/conversation"

payload = json.dumps({
    "app_id": app_id
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': beaver
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
conversation_id = json.loads(response.text)["conversation_id"]
print("输出的会话id：" + conversation_id)

# 步骤二（可选，若对话时上传文件使用）
url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"

payload = {
    'app_id': app_id,
    'conversation_id': conversation_id,
}

files = [
    ('file', ('1.jpg', open('C:\\Users\\zh512st058\\Desktop\\1.jpg', 'rb'), 'image/jpeg'))
]
headers = {
    'X-Appbuilder-Authorization': beaver
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)

file_id = json.loads(response.text)["id"]
print("输出的图片id：" + file_id)

# 步骤三 把问题和参考图片一起输入Agent（自己在Appbuilder中创建并发布的)

url = "https://qianfan.baidubce.com/v2/app/conversation/runs"

payload = json.dumps({
    "app_id": app_id,
    # 用户输入
    "query": input("请输入你的问题："),
    "stream": False,
    # 前一个新建会话接口的返回结果
    "conversation_id": conversation_id,
    "file_ids": [
        file_id
    ]
})
headers = {
    'Content-Type': 'application/json',
    'X-Appbuilder-Authorization': beaver
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
answer = json.loads(response.text)["answer"]